/****
 * 
 * JS AJAX
 * 
 * @author yueya
 * @date 2014 12 12
 * 
 * 创建的xhr对象，它对应有5状态(readyState属性)
 * 0 Uninitialized（尚未调用open方法）
 * 1 Loading （已调用open，尚未调用send）
 * 2 Loaded (已经调用send，尚未接收到响应)
 * 3 Interactive （开始接收数据）
 * 4 Complete (数据接收完毕，响应内容解析完成)
 * 
 */
function Ajax(){

	var self = this;
	var xhr = null;
	var status = ""; //enuc{stop, getting, posting}
	var check = null;

	var constructor = function(){
//		if(navigator.userAgent.indexOf("MSIE")>0){
//			alert(navigator.userAgent.indexOf("MSIE"));
//		}
	
		//创建 XMLHttp 对象
		if (window.XMLHttpRequest) { //如果浏览器类型为Mozilla, Safari,...
			xhr = new XMLHttpRequest();
			/* 有些版本的 Mozilla 浏览器在伺服器送回的资料未含 XML mime-type 
			 * 档头（header）时会出错。为了避免这个问题，可以用下列方法覆写伺服器传回的档头，以免传回的不是 text/xml。 */
			if(xhr.overrideMimeType)xhr.overrideMimeType('text/xml');//如果服务器的响应没有XML mime-type header，则修改之
		}else if(window.ActiveXObject){ // 判定浏览器是 IE
			try{
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			}catch (e){
				try {
					xhr = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
			
		if(!xhr){
			alert('Giving up :( Cannot create an XMLHTTP instance');
			return false;
		}

		status = "stop";
	}();
	
	var setStatus = function(_status){
		status = _status;
	}
	
	var setStatusStop = function(){
//		console.log("setStatusStop ");
		clearInterval(check);
		status = "stop";
	}
	
	this.onError = function(errInfo){}
	this.loaded = function(xhr, url, resulttype, callback){

		var text = "";
		try{
			text = xhr.responseText;
		}catch(e){
			alert('无法得到结果 '+url+'');
			return false;
		}
		
		if(resulttype.toUpperCase() == "TEXT"){
			
			if(callback && (callback instanceof Function)){ callback(text); }

		}else if(resulttype.toUpperCase() == "JSON"){
			try{
				json = eval('(' + text + ')');
			}catch(e){
				alert('无法解析，结果非JSON格式。原文本：'+text+'');
				return false;
			}
			if(callback && (callback instanceof Function)){ callback(json); }
		}else{
			
		}
	};
	
	var checkFinish = function(cBack){
//		console.log("开始检测是否完成");
		if(status != "stop"){
			setStatusStop();
			xhr.abort();
			cBack();
		}
	}
	
	this.get = function(param){
		var url = (typeof(param.url) != "string") ? "" : param.url;
		var timeout = (typeof(param.timeout) != "number") ? 5000 : param.timeout;
		var resultType = (typeof(param.resultType) == "string" && param.resultType == "json") ? "json" : "text";
		var onLoaded = (typeof(param.onLoaded) != "function") ? function(){} : param.onLoaded;
		var onTimeout = (typeof(param.onTimeout) != "function") ? function(){} : param.onTimeout;

		if(status == "stop"){
			setStatus("getting");
			check = setInterval(function(){checkFinish(onTimeout)}, timeout);

			xhr.open('GET', url, true);
			xhr.setRequestHeader("If-Modified-Since","0");//IE系列浏览器会缓存结果页。加上这句话防止缓存
			xhr.onreadystatechange = function(){
//				console.log("onreadystatechange "+xhr.readyState);
				if(xhr.readyState == 4){
					if(xhr.status == 200){
						self.loaded(xhr, url, resultType, onLoaded);
						setStatusStop();
					}else{
						if(status != "stop"){
							self.onError('无法访问 URL:　'+url+'　地址错误或服务器繁忙');
						}
					}
				}
			}
			xhr.send(null);
		}
	}
	
	this.post = function(param){
		var url = (typeof(param.url) != "string") ? "" : param.url;
		var data = (typeof(param.data) != "string") ? "" : param.data;
		var timeout = (typeof(param.timeout) != "number") ? 5000 : param.timeout;
		var resultType = (typeof(param.resultType) == "string" && param.resultType == "json") ? "json" : "text";
		var onLoaded = (typeof(param.onLoaded) != "function") ? function(){} : param.onLoaded;
		var onTimeout = (typeof(param.onTimeout) != "function") ? function(){} : param.onTimeout;
		
		if(status == "stop"){
			setStatus("posting");
			check = setInterval(function(){checkFinish(onTimeout)}, timeout);
			
			xhr.open('POST', url, true);
	//		xhr.setRequestHeader("Cache-Control","no-cache"); // 此处可以注释掉
			xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.status == 200){
						self.loaded(xhr, url, resultType, onLoaded);
						setStatusStop();
					}else{
						if(status != "stop"){
							self.onError('无法访问 URL:　'+url+'　地址错误或服务器繁忙');
						}
					}
				}
			}
			xhr.send(data);
		}
	}
	
}